<template>
  <div class="page-container">
    <SearchForm
        :search-list="searchList"
        :search-params="searchParams"
        @search="onSearch"
        @reset="onReset"
    />
    <el-tabs v-model="searchParams.status_value" @tab-click="handleClick">
      <el-tab-pane label="全部" name="all"></el-tab-pane>
      <el-tab-pane label="待付款" name="wait_pay"></el-tab-pane>
      <el-tab-pane label="已支付" name="paid"></el-tab-pane>
      <el-tab-pane label="已退款" name="refunded"></el-tab-pane>
      <el-tab-pane label="已取消" name="canceled"></el-tab-pane>
    </el-tabs>
    <div class="table-box">
      <el-table
          v-loading="loading"
          height="100%"
          :data="tableData"
          element-loading-spinner="el-icon-loading"
          element-loading-background="rgba(255, 255, 255, 0.8)"
          @selection-change="onSelect"
      >
        <el-table-column label="订单号" prop="order_no" width="120px" fixed="left"></el-table-column>
        <el-table-column label="行程" prop="ship.name" width="150px"></el-table-column>
        <el-table-column label="状态" prop="amount" fixed="left">
          <template slot-scope="scope">
            <el-tag type="primary" v-if="scope.row.status_value === 'wait_pay'">待支付</el-tag>
            <el-tag type="info" v-if="scope.row.status_value === 'canceled'">已取消</el-tag>
            <el-tag type="success" v-if="scope.row.status_value === 'paid'">已支付</el-tag>
            <el-tag type="error" v-if="scope.row.status_value === 'refunded'">已退款</el-tag>
          </template>
        </el-table-column>
        <el-table-column label="代理商" prop="user.nickname" min-width="120px"></el-table-column>
        <el-table-column label="代理商邮箱" prop="user.email"  min-width="120px"></el-table-column>
        <el-table-column label="代理商电话" prop="user.phone"  min-width="120px"></el-table-column>
        <el-table-column label="总人数" prop="count" width="60px"></el-table-column>
        <el-table-column label="总价" prop="amount" width="60px" />
        <el-table-column label="实际费用" prop="amount" width="80px">
          <template slot-scope="scope">
            {{ parseFloat((scope.row.amount * 0.8).toFixed(2)) }}
          </template>
        </el-table-column>
        <el-table-column label="下单时间" prop="create_time" width="150px"></el-table-column>
        <el-table-column label="行程时间" prop="cycle.start_time" min-width="160px"></el-table-column>
        <el-table-column label="行程时长" prop="cycle.duration" min-width="100px"></el-table-column>
        <el-table-column label="IP" prop="ip" min-width="120px"/>
        <el-table-column label="国家" prop="country" min-width="120px"/>
        <el-table-column label="操作" fixed="right" width="120px">
          <template slot-scope="scope">
            <el-button
                type="text" @click="onRead(scope.row)">详情</el-button>
            <el-button
                type="text"
                v-if="scope.row.status_value === 'canceled'"
                style="color: #F82222" @click="onDelete(scope.row)">删除</el-button>
          </template>
        </el-table-column>
      </el-table>
    </div>
    <div class="page-box">
      <el-pagination
          background
          :current-page="pageNo"
          :page-sizes="pageSizes"
          :page-size="pageSize"
          layout="total, sizes, prev, pager, next, jumper"
          :total="totalSize"
          @size-change="changePageSize"
          @current-change="changePageNo"
      />
    </div>

    <!-- 退款弹窗 -->
    <el-dialog
        title="订单退款"
        :visible.sync="refundDialogVisible"
        width="500px"
        :close-on-click-modal="false"
    >
      <el-form
          ref="refundForm"
          :model="refundForm"
          :rules="refundRules"
          label-width="100px"
          size="small"
      >
        <el-form-item label="订单号">
          <span>{{ currentOrder.order_no }}</span>
        </el-form-item>
        <el-form-item label="订单金额">
          <span>${{ currentOrder.amount }}</span>
        </el-form-item>
        <el-form-item label="退款金额" prop="amount">
          <el-input-number
              v-model="refundForm.amount"
              :min="0"
              :max="currentOrder.amount"
              :precision="2"
              :step="1"
              style="width: 200px"
          ></el-input-number>
        </el-form-item>
        <el-form-item label="退款原因" prop="note">
          <el-input
              type="textarea"
              v-model="refundForm.note"
              :rows="3"
              placeholder="请输入退款原因"
          ></el-input>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="refundDialogVisible = false">取 消</el-button>
        <el-button type="primary" :loading="refundLoading" @click="submitRefund">确 定</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import crud from '@/mixins/crud'
import { http } from '@/api'
export default {
  components: {
  },
  mixins: [crud],
  data() {
    return {
      activeName: 'all',
      request: http.order,
      searchList: [
        {
          key: 'ship_id',
          name: 'select',
          label: '出海项目',
          options: [
          ]
        },
        {
          key: 'start_time',
          name: 'datetime',
          label: '开始时间',
          dateType: 'date',
          colSpan: 6,
          width: '240px'
        },
        {
          key: 'end_time',
          name: 'datetime',
          label: '结束时间',
          dateType: 'date',
          colSpan: 6,
          width: '240px'
        },
      ],
      searchParams: {
        status_value: 'all',
        start_time: '',
        end_time: '',
        ship_id: ''
      },
      resetParams: {
        status_value: 'all',
      },
      defaultParams: {
        role: 2
      },
      tableData: [],
      // 退款相关
      refundDialogVisible: false,
      refundLoading: false,
      currentOrder: {},
      refundForm: {
        amount: 0,
        note: ''
      },
      refundRules: {
        amount: [
          { required: true, message: '请输入退款金额', trigger: 'blur' },
          { type: 'number', message: '退款金额必须为数字' }
        ],
        note: [
          { required: true, message: '请输入退款原因', trigger: 'blur' },
          { min: 2, max: 200, message: '长度在 2 到 200 个字符', trigger: 'blur' }
        ]
      }
    }
  },
  created() {
    http.ship.list().then(res => {
      this.searchList[0].options = res.data.map(el => ({ name: el.name, value: el.id }))
    })
  },
  methods: {
    handleClick() {
      this.onSearch()
    },
    onAdd() {
      this.$refs.addFormRef.open()
    },
    onEdit(row) {
      this.$refs.addFormRef.open(row)
    },
    onRefund(row) {
      this.currentOrder = {
        ...row,
        amount: Number(row.amount)
      }
      this.refundForm.amount = Number(row.amount)
      this.refundDialogVisible = true
    },
    async submitRefund() {
      try {
        await this.$refs.refundForm.validate()

        this.refundLoading = true
        const response = await http.payment.paypalRefund({
          orderId: this.currentOrder.id,
          amount: this.refundForm.amount,
          note: this.refundForm.note
        })

        if (response.code === 200) {
          this.$message.success('退款申请成功')
          this.refundDialogVisible = false
          this.initData()
        } else {
          this.$message.error(response.message || '退款失败')
        }
      } catch (error) {
        console.error('Refund Error:', error)
        this.$message.error(error.message || '退款失败')
      } finally {
        this.refundLoading = false
      }
    },
    onCancel(row) {
      this.$confirm('确定要取消该订单吗？', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(async () => {
        try {
          const response = await http.order.cancel(row.id)
          if (response.code === 200) {
            this.$message.success('订单已取消')
            this.initData()
          } else {
            this.$message.error(response.message || '取消失败')
          }
        } catch (error) {
          console.error('Cancel Error:', error)
          this.$message.error(error.message || '取消失败')
        }
      }).catch(() => {})
    },
    onDelete(row) {
      this.$confirm('确定要删除该订单吗？该操作不可恢复！', '警告', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(async () => {
        try {
          const response = await http.order.delete(row.id)
          if (response.code === 200) {
            this.$message.success('订单已删除')
            this.initData()
          } else {
            this.$message.error(response.message || '删除失败')
          }
        } catch (error) {
          console.error('Delete Error:', error)
          this.$message.error(error.message || '删除失败')
        }
      }).catch(() => {})
    },
    onRead(row) {
      this.$router.push({
        name: 'orderDetail',
        query: {
          orderId: row.id
        }
      })
    }
  }
}
</script>

<style scoped lang="scss">
.page-container {
  padding: 20px;
  height: 100%;
  box-sizing: border-box;
  display: flex;
  flex-direction: column;
}

.table-box {
  flex: 1;
  margin: 20px 0;
  overflow: hidden;

  .el-table {
    height: 100% !important;
  }
}

.page-box {
  display: flex;
  justify-content: flex-end;
  margin-top: 20px;
}

.dialog-footer {
  text-align: right;
}
</style>
